/**
 * Toggle Button - jQuery EasyUI Extension
 * 
 * Copyright (c) 2009-2013 Rime Lee. All rights reserved.
 */
(function($) {
	$.fn.togglebutton = function(options, param) {
		if (typeof options == 'string') {
			var method = $.fn.togglebutton.methods[options];
			if (method) {
				return method(this, param);
			} else {
				return this.linkbutton(options, param);
			}
		}

		options = options || {};
		return this.each(function() {
			var d = $.data(this, 'togglebutton');
			if (d) {
				$.extend(d.options, options);
			} else {
				var opts = $.extend({}, $.fn.togglebutton.defaults, options);
				d = {
					flag : 1,
					options : opts
				};
				$.data(this, 'togglebutton', d);
				$(this).bind('click', function(e) {
					if (d.flag == 2) {
						if (opts.onSwitch) {
							opts.onSwitch.call(this, false);
						}
						d.flag = 1;
					} else {
						if (opts.onSwitch) {
							opts.onSwitch.call(this, true);
						}
						d.flag = 2;
					}
					updateButton(this, d);
				});
			}
			updateButton(this, d);
		});
	};

	function updateButton(target, data) {
		if (data && data.options) {
			var o = {
				disabled : data.options.disabled,
				plain : data.options.plain,
				iconAlign : data.options.iconAlign
			};
			if (data.flag && (data.flag == 2)) {
				o.text = data.options.text2;
				o.iconCls = data.options.icon2;
			} else {
				o.text = data.options.text1;
				o.iconCls = data.options.icon1;
			}
			$(target).linkbutton(o);
		}
	}

	$.fn.togglebutton.methods = {
		options : function(jq) {
			return $.data(jq[0], 'togglebutton').options;
		},
		switchOn : function(jq, param) {
			return jq.each(function() {
				var d = $.data(this, 'togglebutton');
				d.flag = 2;
				updateButton(this, d);
			});
		},
		switchOff : function(jq, param) {
			return jq.each(function() {
				var d = $.data(this, 'togglebutton');
				d.flag = 1;
				updateButton(this, d);
			});
		}
	};

	$.fn.togglebutton.defaults = $.extend({}, $.fn.linkbutton.defaults, {
		icon1 : null,
		icon2 : null,
		text1 : null,
		text2 : null,
		onSwitch : function(on) {
		}
	});
})(jQuery);